﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Kindohm.Life.Library
{
    public class Corpse : HeartbeatObject, IEdible
    {
        int nutritionDecreaseThreshold;
        int nutritionDecreaseHeartbeats;
        int decayThreshold;
        int nutrition;

        private Corpse()
        {
        }

        public static Corpse Create()
        {
            Corpse corpse = new Corpse();
            corpse.decayThreshold = NormalGenerator.Next(100, 20);
            corpse.nutritionDecreaseThreshold = NormalGenerator.Next(15, 3);
            return corpse;
        }

        public int NutritionDecreaseThreshold
        {
            get { return this.nutritionDecreaseThreshold; }
            set { this.nutritionDecreaseThreshold = value; }
        }

        public int NutritionDecreaseHeartbeats
        {
            get { return this.nutritionDecreaseHeartbeats; }
            set { this.nutritionDecreaseHeartbeats = value; }
        }

        public int Nutrition
        {
            get { return this.nutrition; }
            set { this.nutrition = value; }
        }

        public void BeEaten()
        {
            this.nutrition = 0;
        }

        public override void RunHeartbeat()
        {
            base.RunHeartbeat();
            if (!this.Done)
            {

                if (this.nutrition > 0)
                {
                    this.nutritionDecreaseHeartbeats++;

                    if (this.nutritionDecreaseHeartbeats >= this.nutritionDecreaseThreshold)
                    {
                        this.nutrition--;
                        this.nutritionDecreaseHeartbeats = 0;
                    }
                }

                if (this.Heartbeats >= this.decayThreshold)
                {
                    this.nutrition = 0;
                    this.ProduceStuff();
                }
            }
        }

        void ProduceStuff()
        {
            this.Done = true;
            Point position = this.Position;
            Plant plant = Plant.Create();

            this.RemoveFromBoard();
            if (this.Board != null)
            {
                this.Board.AddObject(plant, position);
            }
            if (this.World != null)
            {
                this.World.RegisterNewObject(plant);
            }

            if (this.ProducedPlant != null)
            {
                this.ProducedPlant(this, EventArgs.Empty);
            }
        }

        public int DecayThreshold
        {
            get { return this.decayThreshold; }
            set { this.decayThreshold = value; }
        }

        public event EventHandler<EventArgs> ProducedPlant;

    }
}
